package com.pr.makfilm.user.pages.school.list.cmp;

import com.pr.makfilm.core.cmp.notify.Notification;
import com.pr.makfilm.core.cmp.web.BootstrapTextArea;
import com.pr.makfilm.core.cmp.web.BootstrapTextFieldPanel;
import com.pr.makfilm.core.cmp.window.AbstractWindow;
import com.pr.makfilm.domain.SchoolType;
import com.pr.makfilm.service.ISchoolTypeService;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.StringValidator;

/**
 * Created with IntelliJ IDEA.
 * User: Pawel
 * Date: 23.09.13
 * Time: 22:32
 * To change this template use File | Settings | File Templates.
 */
public abstract class TypeWindow extends AbstractWindow<SchoolType>
{
   @SpringBean
   private ISchoolTypeService schoolTypeService;

   private boolean createMode = true;

   public TypeWindow(String id)
   {
      super(id, Model.of(new SchoolType()), new Model<String>());
   }

   @Override
   protected void onInitialize()
   {
      super.onInitialize();
      BootstrapTextFieldPanel name = new BootstrapTextFieldPanel("name",
              new PropertyModel(this, "type." + SchoolType.FIELD_NAME));
      name.setValidation(true);
      name.getField().add(StringValidator.maximumLength(SchoolType.MAX_LENGTH_NAME));
      form.add(name);

      BootstrapTextArea description = new BootstrapTextArea("description",
              new PropertyModel(this, "type." + SchoolType.FIELD_DESCRIPTION));
      description.setValidation(false);
      form.add(description);
   }

   @Override
   public void onSubmit(AjaxRequestTarget target, Form<?> form)
   {
      SchoolType type = getType();
      if (createMode())
      {
         schoolTypeService.save(type);
         Notification.success(getString("type.successfully.saved"));
      }
      else
      {
         SchoolType old = schoolTypeService.getBySid(type.getSid());
         old.setName(type.getName());
         old.setDescription(type.getDescription());
         schoolTypeService.update(old);
         Notification.success(getString("type.successfully.updated"));
      }
   }

   public void resetState(boolean createMode)
   {
      this.createMode = createMode;
      if (createMode)
      {
         setType(new SchoolType());
      }
      headerModel.setObject(createMode ? getString("create.title") : getString("edit.title"));
   }

   public boolean createMode()
   {
      return createMode;
   }

   public SchoolType getType()
   {
      return (SchoolType) getDefaultModelObject();
   }

   public void setType(SchoolType type)
   {
      setDefaultModelObject(type);
   }
}
